<template>
  <div class="header-content">
    <div class="header-actions">
      <el-button type="primary" text size="small" @click="handleAdd">
        <el-icon><Plus /></el-icon> 添加主题
      </el-button>
      <el-tooltip content="主题支持通配符 #(多级)和 +(单级)" placement="top">
        <el-icon class="tip-icon"><InfoFilled /></el-icon>
      </el-tooltip>
    </div>

    <el-table
      :data="topics"
      border
      style="width: 100%"
      empty-text="暂无主题配置"
      class="topic-table"
    >
      <el-table-column prop="topic" label="主题" min-width="300" />
      <el-table-column prop="qos" label="QoS" width="120" align="center">
        <template #default="{ row }">
          {{ qosLabel(row.qos) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            circle
            @click="handleEdit(row, $index)"
          />
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            circle
            @click="confirmRemove($index)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="topicForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="主题" prop="topic">
          <el-input v-model="topicForm.topic" placeholder="例如: sensor/data/#" />
          <div class="form-tip">支持通配符 #(多级)和 +(单级)</div>
        </el-form-item>

        <el-form-item label="QoS等级" prop="qos">
          <el-radio-group v-model="topicForm.qos">
            <el-radio-button :value="0">QoS 0 - 最多一次</el-radio-button>
            <el-radio-button :value="1">QoS 1 - 至少一次</el-radio-button>
            <el-radio-button :value="2">QoS 2 - 恰好一次</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="topicForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="loading">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, InfoFilled, Edit } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

interface MqttTopicField {
  topic: string
  qos: number
  remark?: string
}

const props = defineProps<{ 
  data: MqttTopicField[]
}>()

const emit = defineEmits(['update:data'])

const topics = computed({
  get: () => props.data,
  set: (value) => emit('update:data', value)
})

const dialog = reactive({
  visible: false,
  title: '',
  mode: 'add', // 'add' | 'edit'
  editIndex: -1
})

const loading = ref(false)
const formRef = ref<FormInstance>()

const topicForm = reactive({
  topic: '',
  qos: 0,
  remark: ''
})

const rules = reactive<FormRules>({
  topic: [
    { required: true, message: '主题不能为空', trigger: 'blur' },
    { 
      validator: (_rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        
        // 验证主题格式
        if (!/^[^#+]+(\/[^#+]+)*(\/?#?|\/+)?$/.test(value)) {
          callback(new Error('主题格式无效，可使用#(多级)或+(单级)通配符'))
          return
        }
        
        // 检查重复主题（编辑模式下排除当前编辑项）
        const duplicate = topics.value.some((t, i) => {
          return t.topic === value && 
            (dialog.mode === 'add' || i !== dialog.editIndex)
        })
        
        if (duplicate) {
          callback(new Error('主题已存在'))
          return
        }
        
        callback()
      },
      trigger: 'blur'
    }
  ],
  qos: [
    { required: true, message: '请选择QoS等级', trigger: 'change' }
  ]
})

// 添加主题
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '添加主题'
  dialog.mode = 'add'
  dialog.editIndex = -1
  
  // 重置表单
  Object.assign(topicForm, {
    topic: '',
    qos: 0,
    remark: ''
  })
  
  // 清除验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 编辑主题
const handleEdit = (row: MqttTopicField, index: number) => {
  dialog.visible = true
  dialog.title = '编辑主题'
  dialog.mode = 'edit'
  dialog.editIndex = index
  
  // 填充表单数据
  Object.assign(topicForm, {
    topic: row.topic,
    qos: row.qos,
    remark: row.remark || ''
  })
  
  // 清除验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 取消
const handleCancel = () => {
  dialog.visible = false
}

// 确认
const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    const newTopic = {
      topic: topicForm.topic.trim(),
      qos: topicForm.qos,
      remark: topicForm.remark.trim()
    }
    
	
    if (dialog.mode === 'add') {
      // 添加新主题
      topics.value = [...topics.value, newTopic]
	  
	  topics.value.push(newTopic);
	  
    } else {
      topics.value[dialog.editIndex] = newTopic
    }
    ElMessage.success(dialog.mode === 'add' ? '添加成功' : '更新成功')
    dialog.visible = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 确认删除
const confirmRemove = (index: number) => {
  ElMessageBox.confirm('确定删除该主题配置吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
	topics.value.splice(index, 1);
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// QoS标签显示
const qosLabel = (qos: number) => {
  return `${qos} - ${
    qos === 0 ? '最多一次' : 
    qos === 1 ? '至少一次' : '恰好一次'
  }`
}

// 验证所有主题
const validate = (): boolean => {
  if (topics.value.length === 0) {
    ElMessage.warning('请至少添加一个主题配置')
    return false
  }
  
  // 检查是否有重复主题
  const topicSet = new Set()
  let hasError = false
  
  for (const topic of topics.value) {
    if (topicSet.has(topic.topic)) {
      ElMessage.warning(`发现重复主题: ${topic.topic}`)
      hasError = true
      break
    }
    
    if (!topic.topic.trim()) {
      ElMessage.warning('主题不能为空')
      hasError = true
      break
    }
    
    if (!/^[^#+]+(\/[^#+]+)*(\/?#?|\/+)?$/.test(topic.topic)) {
      ElMessage.warning(`主题格式无效: ${topic.topic}`)
      hasError = true
      break
    }
    
    topicSet.add(topic.topic)
  }
  
  return !hasError
}

// 暴露方法
defineExpose({
  validate,
  getData: () => topics.value.filter(t => t.topic.trim())
})
</script>

<style scoped>
.header-content {
  border-radius: 4px;
  padding: 12px;
  background-color: var(--el-bg-color);
}

.header-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tip-icon {
  color: var(--el-color-info);
  cursor: help;
}

.topic-table {
  margin-top: 8px;
}

:deep(.el-table__row) td {
  padding: 8px 0;
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>